using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LocalDnsSdk.Formatting
{
    public static class TextTableFormatter
    {
        // 与服务中的签名保持一致，便于替换调用
        public static string FormatAlignedTable(IReadOnlyList<string[]> rows, int padding = 2, int maxColumnWidth = 80)
        {
            if (rows == null || rows.Count == 0) return string.Empty;
            int columnCount = rows.Max(r => r.Length);
            var widths = new int[columnCount];
            for (int i = 0; i < columnCount; i++)
            {
                widths[i] = rows.Max(r => i < r.Length ? (r[i]?.Length ?? 0) : 0);
                if (widths[i] > maxColumnWidth) widths[i] = maxColumnWidth;
            }
            var sb = new StringBuilder();
            foreach (var row in rows)
            {
                for (int i = 0; i < columnCount; i++)
                {
                    var cell = i < row.Length ? (row[i] ?? string.Empty) : string.Empty;
                    if (cell.Length > maxColumnWidth) cell = cell.Substring(0, maxColumnWidth);
                    sb.Append(cell.PadRight(widths[i] + (i < columnCount - 1 ? padding : 0)));
                }
                sb.AppendLine();
            }
            return sb.ToString().TrimEnd();
        }
    }
}